package com.gusti.turnos.services.impl;

import java.util.GregorianCalendar;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gusti.turnos.exception.TurnosException;
import com.gusti.turnos.form.AppointmentForm;
import com.gusti.turnos.model.Appointment;
import com.gusti.turnos.model.User;
import com.gusti.turnos.response.rest.TurnosResponse;
import com.gusti.turnos.services.AbstractService;
import com.gusti.turnos.services.IAppointmentService;
import com.gusti.turnos.util.MessageUtil;

/**
 * 
 * @author gusti
 *
 */
@Service
public class AppointmentService extends AbstractService implements IAppointmentService {

	@Override
	public List<Appointment> retrieveAppointments() {

		List<Appointment> appointments = appointmentDao.retrieveAppointments();

		return appointments;
	}

	@Override
	public Appointment retrieveAppointment( long id ) {

		Appointment appointment = appointmentDao.retrieveAppointment( id );

		return appointment;
	}

	@Override
	public TurnosResponse retrieveAppointments( String sessionId, String uuid ) {

		checkAuthenticationCredentials( sessionId, uuid );

		List<Appointment> appointments = retrieveAppointments();

		TurnosResponse turnosResponse = new TurnosResponse();
		turnosResponse.setSuccess( true );
		turnosResponse.setData( appointments );

		return turnosResponse;
	}

	@Override
	@Transactional
	public TurnosResponse saveAppointment( String sessionId, String uuid, AppointmentForm appointmentForm ) {

		checkAuthenticationCredentials( sessionId, uuid );
		checkUserAdminLevel();

		TurnosResponse turnosResponse = new TurnosResponse();

		//check unique name
		if( !appointmentDao.checkUniqueField( Appointment.class.getSimpleName(), "name", appointmentForm.getName() ) ) {
			throw new TurnosException( MessageUtil.getMessage( MessageUtil.ERROR_APPOINTMENT_NAME_USED ) );
		}

		//create the new appointment
		Appointment appointment = new Appointment();
		appointment.setName( appointmentForm.getName() );
		appointment.setFromHour( appointmentForm.getFromHour() );
		appointment.setToHour( appointmentForm.getToHour() );

		//save appointment
		appointment = appointmentDao.save( appointment );

		if( appointment.isNew() ) {
			turnosResponse.setErrorMessage( MessageUtil.getMessage( MessageUtil.ERROR_SAVE ) );
		} else {
			turnosResponse.setSuccess( true );
			turnosResponse.setData( appointment );
		}

		return turnosResponse;
	}

	@Override
	@Transactional
	public TurnosResponse deleteAppointment( String sessionId, String uuid, String id ) {

		checkAuthenticationCredentials( sessionId, uuid );
		checkUserAdminLevel();

		TurnosResponse turnosResponse = new TurnosResponse();

		return turnosResponse;
	}
}
